import { registerFunction } from './autoRoute';

// 路由配置接口
interface RouteConfig {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  path?: string;
  auth?: boolean;
  middleware?: Function[];
}

// 路由装饰器
export function Route(config: RouteConfig) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    if (!target.__routes) {
      target.__routes = [];
    }
    target.__routes.push({
      name: propertyKey,
      func: descriptor.value,
      config
    });
  };
}

// 自动生成路由路径
function generatePath(serviceName: string, methodName: string): string {
  // 移除Service后缀
  const cleanServiceName = serviceName.replace(/Service$/, '').toLowerCase();
  
  // 处理方法名
  let path = methodName;
  if (path.startsWith('get')) path = path.substring(3);
  else if (path.startsWith('create')) path = path.substring(6);
  else if (path.startsWith('update')) path = path.substring(6);
  else if (path.startsWith('delete')) path = path.substring(6);
  
  // 转换为路径格式
  const methodPath = path.replace(/([A-Z])/g, '/$1').toLowerCase();
  const cleanMethodPath = methodPath.startsWith('/') ? methodPath.substring(1) : methodPath;
  
  return `/${cleanServiceName}${cleanMethodPath ? '/' + cleanMethodPath : ''}`;
}

// 自动检测HTTP方法
function detectMethod(methodName: string): 'GET' | 'POST' | 'PUT' | 'DELETE' {
  if (methodName.startsWith('get') || methodName.startsWith('list') || methodName.startsWith('find')) {
    return 'GET';
  } else if (methodName.startsWith('create') || methodName.startsWith('add')) {
    return 'POST';
  } else if (methodName.startsWith('update') || methodName.startsWith('edit') || methodName.startsWith('modify')) {
    return 'PUT';
  } else if (methodName.startsWith('delete') || methodName.startsWith('remove')) {
    return 'DELETE';
  }
  return 'GET'; // 默认
}

// 基础服务类
export class AutoService {
  constructor() {
    this.autoRegister();
  }

  // 自动注册所有方法为路由
  private autoRegister() {
    const serviceName = this.constructor.name;
    const prototype = Object.getPrototypeOf(this);
    
    // 获取所有方法名
    const methodNames = Object.getOwnPropertyNames(prototype)
      .filter(name => 
        name !== 'constructor' && 
        name !== 'autoRegister' &&
        typeof prototype[name] === 'function' &&
        !name.startsWith('_') // 私有方法不注册
      );

    // 处理装饰器标记的路由
    const decoratedRoutes = (prototype.__routes || []);
    const decoratedMethods = new Set(decoratedRoutes.map((r: any) => r.name));

    // 注册装饰器路由
    decoratedRoutes.forEach((route: any) => {
      registerFunction(route.name, route.func.bind(this), route.config);
      console.log(`📍 装饰器路由: ${route.config.method || 'GET'} ${route.config.path} -> ${route.name}`);
    });

    // 自动注册其他方法
    methodNames
      .filter(name => !decoratedMethods.has(name))
      .forEach(methodName => {
        const method = prototype[methodName].bind(this);
        const httpMethod = detectMethod(methodName);
        const path = generatePath(serviceName, methodName);
        
        registerFunction(methodName, method, {
          method: httpMethod,
          path: path,
          auth: true // 默认需要认证
        });
        
        console.log(`🤖 自动路由: ${httpMethod} ${path} -> ${methodName}`);
      });
  }
}

// 自动扫描并注册函数（用于函数式编程）
export function autoRegisterFunctions(obj: any, serviceName: string) {
  Object.getOwnPropertyNames(obj)
    .filter(name => typeof obj[name] === 'function')
    .forEach(functionName => {
      const func = obj[functionName];
      const httpMethod = detectMethod(functionName);
      const path = generatePath(serviceName, functionName);
      
      registerFunction(functionName, func, {
        method: httpMethod,
        path: path,
        auth: true
      });
      
      console.log(`🔍 扫描注册: ${httpMethod} ${path} -> ${functionName}`);
    });
}

// 简化装饰器
export const GET = (path?: string) => Route({ method: 'GET', path });
export const POST = (path?: string) => Route({ method: 'POST', path });
export const PUT = (path?: string) => Route({ method: 'PUT', path });
export const DELETE = (path?: string) => Route({ method: 'DELETE', path });
export const Public = (config: Omit<RouteConfig, 'auth'> = {}) => Route({ ...config, auth: false }); 